<%@page language="java" isELIgnored="false" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<jsp:directive.include file="/WEB-INF/sitemesh-decorators/include.jsp" />
<c:set var="menu" value="group" scope="request" />

<html>
<head>
<title>Groups</title>
<script type="text/javascript">
   $(document).ready(function () {
      $("#btnUpdatePermission").jqxButton({ theme: getSowTheme('ui-redmond') });
      $("#btnAddUser").jqxButton({ width : 50, theme: getSowTheme('ui-redmond') });
      makeCenter2("ajax-loader");
      makeCenter2("loading");
      $('#ajax-loader').hide();
      $('#loading').hide();
      
      $("#users").tokenInput("${pageContext.request.contextPath}/ajax/user/search", {
         theme: "facebook",
         queryParam : "approver",
         preventDuplicates: true,
         resultsFormatter: function(item) { return "<li>" + "<div><img src='${pageContext.request.contextPath}/images/default_profile.png' title='" + item.name + "' height='40px' width='40px' />" + "<div style='display: inline-block; vertical-align: top; padding: 0px 0px 0px 5px'><span style='display:block'>" + item.name + "</span><span>" + item.username + "</span></div></div></li>"; },
         tokenFormatter: function(item) { return "<li><p>" + item.name + "</p></li>"; }
      });
      
      var source = {
         datatype: "json",
         datafields: [
			{ name: 'id' },
            { name: 'name' }
         ],
         id: 'id',
         url: "<c:url value='/admin/group/${id}/users' />",
         async: false
      };

      var dataAdapter = new $.jqx.dataAdapter(source);

      $("#userListbox").jqxListBox({ source: dataAdapter, displayMember: "name", valueMember: "id", width: 228, height: 250, theme: getTheme(), enableSelection: false,
         renderer: function (index, label, value) {
            var div = '<div style="float: left">' + label + '</div><div style="float: right"><a onclick="openRemoveDiaglog(' + value + ');" href="javascript:;"><span class="ui-icon ui-icon-closethick remove-sow">remove</span></a></div>';
            return div;
        }
      });
   });
   
   function openRemoveDiaglog(id) {
      $("#removeDialog").dialog({
         resizable: false,
         draggable: false,
         modal: true,
         width: 300,
         buttons: {
            "Remove user": function() {
               $(this).dialog("close");
               removeUserFromGroup(id);
   			},
   			Cancel: function() {
   				$(this).dialog("close");
   			}
         }
      });
   }
   
   function openMessageDiaglog(message) {
      $('#spanMessage').text(message);
      $("#dialog-message").dialog({
         resizable: false,
         draggable: false,
         modal: true,
         buttons: {
   			Ok: function() {
   				$(this).dialog("close");
   			}
         }
      });
   }

   function addUsersToGroup() {
      var items = $('#users').val();
      var userIds = items.split(',');

      $.ajax({
         url : "<c:url value='/admin/group/${id}/users/add' />",
         type : "POST",
         data : { userIds: userIds },
         beforeSend : function() {
            $('#loading').show();
            $("#users").tokenInput("clear");
         },
         complete : function() {
            $('#loading').hide();
         },
         success : function(data) {
            $("#userListbox").jqxListBox("source").dataBind();
         },
         error : function() {
            alert("Failure args: " + arguments);
         }
      });
   }
   
   function removeUserFromGroup(id) {
      $.ajax({
         url : "<c:url value='/admin/group/${id}/user/remove' />",
         type : "POST",
         data : { userId: id },
         beforeSend : function() {
            $('#loading').show();
         },
         complete : function() {
            $('#loading').hide();
         },
         success : function(data) {
            $("#userListbox").jqxListBox("source").dataBind();
         },
         error : function() {
            alert("Failure args: " + arguments);
         }
      });
   }

   function updatePermissions() {
      $.ajax({
         url : "<c:url value='/admin/group/${id}/permissions/update' />",
         type : "POST",
         data: $('#permissionForm').serialize(),
         beforeSend : function() {
            $('#ajax-loader').show();
         },
         complete : function() {
            $('#ajax-loader').hide();
         },
         success : function(data) {
            openMessageDiaglog("The group's permissions have been updated successfully.");
         },
         error : function() {
            alert("Failure args: " + arguments);
         }
      });
   }

   function updateProfile() {
      $.ajax({
         url : "<c:url value='/ajax/admin/group/profile/update' />",
         type : "POST",
         data: $('#groupForm').serialize(),
         dataType : "html",
         success : function(data) {
            $("#groupProfile").html(data);
            if($(data).first().attr("id") != "error") {
            	openMessageDiaglog("The group's profile have been updated successfully.");
            }
         }
      });
   }

   function selectAll(perm) {
      var list = $("input:checkbox[name='" + perm + "']");
      var checked = false;

      list.each(function (index, element) {
         if(!$(element).attr('checked')) {
            checked = true;
         }
      });

      list.each(function (index, element) {
         $(element).attr('checked', checked);
      });
   }
</script>

<link rel="stylesheet" href="<c:url value='/css/PermissionsPanel.css' />" />
<!-- token input -->
<script type="text/javascript" src="${pageContext.request.contextPath}/scripts/tokeninput/jquery.tokeninput.js"></script>
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/tokeninput/token-input.css" type="text/css" />
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/tokeninput/token-input-facebook.css" type="text/css" />
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/tokeninput/custom-token-input.css" type="text/css" />
<!-- end token input -->
<style type="text/css">
   ul.token-input-list-facebook { width: 228px; }
   div.token-input-dropdown-facebook { width: 228px; }
</style>
</head>

<body>
   <div class="cubeTitleWrapper">
      <span class="cube_title">Group</span>
   </div>

   <div class="cube">
      <div>
         <div class="contentwrapper">
            <div class="contentcolumn">
               <div class="innertube">
                  <h2 class="userDefinedBg curved">Group Profile</h2>
                  <div class="contentBlock">
                     <div id="groupProfile"><jsp:directive.include file="/WEB-INF/pages/controls/group_profile_form.jsp" /></div>
                  </div>
                  <div class="contentBlock_bottom"><span class="right_end"><span></span></span></div>

                  <h2 class="userDefinedBg curved">Permission</h2>
                  <div class="contentBlock">
                     <div id="ajax-loader" style="position: absolute;"><img src="<c:url value='/images/ajax-loader.gif' />" /></div>
                     <form id="permissionForm"><input type="hidden" name="test" value="P">
                     <div class="permissionsPanel">
                        <div class="permissionTableHeader">
                           <table>
                              <thead>
                                 <tr class="head">
                                    <th><h3 style="cursor: text;">Document Repositories</h3></th>
                                    <td><span style="cursor: text;">Read</span></td>
                                    <td><span style="cursor: text;">&nbsp;</span></td>
                                    <td><span style="cursor: text;">Write</span></td>
                                    <td><span style="cursor: text;">&nbsp;</span></td>
                                    <td><span style="cursor: text;">Admin</span></td>
                                 </tr>
                              </thead>
                           </table>
                        </div>
                        <div class="permissionTable">
                           <table>
                              <thead>
                                 <tr class="head">
                                    <th><h3 style="cursor: text;"><span>Repository</span><span class="arrow"></span></h3></th>
                                    <td onclick="selectAll('reads')"><span title="Select all"></span></td>
                                    <td>&nbsp;</td>
                                    <td onclick="selectAll('writes')"><span title="Select all"></span></td>
                                    <td>&nbsp;</td>
                                    <td onclick="selectAll('admins')"><span title="Select all"></span></td>
                                 </tr>
                              </thead>
                              <tbody>
                                 <c:forEach items="${repositories}" var="repository" varStatus="i">
                                 <tr style="${i.count % 2 == 0 ? 'background: #efefef;' : ''}" class="accessRight">
                                    <th><span>${repository.name}</span><input type="hidden" name="repositoryIds" value="${repository.id}"></th>
                                    <td title="Read"><input type="checkbox" name="reads" value="${repository.id}" ${repository.read ? 'checked="checked"' : ''}></td>
                                    <td><span>&nbsp;</span></td>
                                    <td title="Write"><input type="checkbox" name="writes" value="${repository.id}" ${repository.write ? 'checked="checked"' : ''}></td>
                                    <td><span>&nbsp;</span></td>
                                    <td title="Admin"><input type="checkbox" name="admins" value="${repository.id}" ${repository.admin ? 'checked="checked"' : ''}></td>
                                 </tr>
                                 </c:forEach>
                              </tbody>
                           </table>
                        </div>
                        
                        <br>
                        <div align="right"><input id="btnUpdatePermission" type="button" value="Update" onclick="updatePermissions()" style="cursor: pointer;" /></div>
                     </div>
                     </form>
                  </div>
                  <div class="contentBlock_bottom"><span class="right_end"><span></span></span></div>
               </div>
            </div>
         </div>

         <div class="rightcolumn">
            <div class="innertube">
               <h2 class="userDefinedBg"><span class="right_end"><span class="start">Members</span></span></h2>
               <div class="contentBlock">
                  <div id="userListbox" style="height: 250px">
                     <div id="loading" style="position: absolute; z-index: 9999;"><img src="<c:url value='/images/ajax-loader.gif' />" /></div>
                  </div>
                  <div id="groupDesc" style="padding-top: 10px">
                     <p style="padding-bottom: 4px">Add users to group:</p>
                     <input type="text" id="users" name="users" />
                  </div><br>
                  <div style="height: 30px; vertical-align:middle;">
                     <div align="right" style="width:80px; float:right;"><input id="btnAddUser" type="button" value="Add" onclick="addUsersToGroup()" style="cursor: pointer;" /></div>
                  </div>
               </div>
               <div class="contentBlock_bottom"><span class="right_end"><span></span></span></div>
            </div>
         </div>
      </div>
   </div>

   <div id="removeDialog" title="Remove this user?" style="display: none;">
      <p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>This user will be removed from the group. Are you sure?</p>
   </div>
   <div id="dialog-message" title="Update success" style="display: none;">
      <p><span class="ui-icon ui-icon-circle-check" style="float:left; margin:0 7px 15px 0;"></span><span id="spanMessage">The group's permissions have been updated successfully.</span></p>
   </div>
</body>
</html>